{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import wave\n",
    "import numpy as np\n",
    "import pylab as plt\n",
    "from scipy.signal import firwin\n",
    "from scipy.signal.signaltools import get_window\n",
    "from scipy.signal import iirnotch, lfilter\n",
    "from numpy.fft import rfft\n",
    "%matplotlib inline\n",
    "np.set_printoptions(precision=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def sample_to_int(data):\n",
    "        d = int.from_bytes(data, byteorder='little', signed=True)\n",
    "        return d\n",
    "\n",
    "def int_to_sample(data):\n",
    "        d = int(data)\n",
    "        return d.to_bytes(3, byteorder='little', signed=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def calc_thd(data):\n",
    "    f = rfft(data)\n",
    "    i = np.argmax(abs(f))\n",
    "    fs = i/len(data)\n",
    "    freq = SR*fs\n",
    "    b, a = iirnotch(fs*2, 1)\n",
    "    filtered_data = lfilter(b, a, data)\n",
    "    filtered_data = filtered_data[1000:]\n",
    "    for i in range(len(filtered_data)):\n",
    "        f_out.writeframes(int_to_sample(filtered_data[i]))\n",
    "    rms_in = np.sqrt(np.mean(np.square(data)))\n",
    "    rms = np.sqrt(np.mean(np.square(filtered_data)))\n",
    "    thd = 20*np.log10(rms/rms_in)\n",
    "    print(\"Frequency: %f THD+N: %.1f dB\" % (freq, thd))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SR = 48000\n",
    "SEC = 1\n",
    "N = int(SR*SEC)\n",
    "fname = \"wave_out.wav\"\n",
    "f = wave.open(fname, 'rb')\n",
    "\n",
    "f_out = wave.open(\"thd.wav\", \"wb\")\n",
    "f_out.setframerate(SR)\n",
    "f_out.setsampwidth(3)\n",
    "f_out.setnchannels(1)\n",
    "\n",
    "data = np.zeros(N)\n",
    "work = True\n",
    "while(work):\n",
    "    for i in range(N):\n",
    "        d = f.readframes(1)\n",
    "        if(len(d)==0):\n",
    "            work = False\n",
    "            break\n",
    "        data[i] = sample_to_int(d)\n",
    "    calc_thd(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "f.close()\n",
    "f_out.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
